<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2017/8/24  19:25
 */
namespace app\business\controller;
use app\api\logic\System;
use app\api\model\DriverOrderInfo;
use think\Request;
use think\Db;
class Order extends Common
{/*
*	构造函数
*/
    function __construct(){
        parent::__construct();

    }

    public function order_list()
    {
        $where=array();
        $status=input('status');
        if(!empty($status)){
            $where['o.status'] =$status;
        }
        if(input("type")!=''){
            $where['o.type'] =input("type");
        }
        $keywords=trim(input('keywords'));
        if(!empty($keywords)){//全部订单
            $where['o.order_sn'] =array("like",'%'.$keywords.'%');
        }
        $member=trim(input('member'));
        if(!empty($member)){//全部订单
            $where['m.nickname|m.mobile'] =array("like",'%'.$member.'%');
        }
         $starttime=trim(input('starttime'));
        if(!empty($starttime)){//全部订单
            $where['o.create_time'] =array("gt",strtotime($starttime));
        }
        $where['o.shop_id'] = $this->user['shopid'];
        $endtime=trim(input('endtime'));
        if(!empty($starttime)){//全部订单
            $where['o.create_time'] =array("gt",strtotime($endtime));
        }
        if(!empty($starttime) && !empty($endtime)){//全部订单
            $where['o.create_time'] =array("between",[strtotime($starttime),strtotime($endtime)]);
        }
        if(input('export')){
            $this->export($where);exit;
        }
        $list = db("order")->alias("o")
            ->field("o.*,m.nickname,m.mobile,m.headimage")
            ->join("member m","o.user_id=m.id")
            ->where($where)
            ->order("o.id desc")
            ->paginate(10);
        $count = db("order")->alias("o")
            ->field("o.*,m.nickname,m.mobile,m.headimage")
            ->join("member m","o.user_id=m.id")
            ->where($where)
            ->count();
       $pay_type=array(
           "0"=>"待支付",
           "1"=>"支付宝",
            "2"=>"支付宝",
            "3"=>"微信",
            "4"=>"百度钱包",
            "5"=>"京东",
            "6"=>"qq钱包",
            "7"=>"NFC支付",
            "8"=>"拉卡拉钱包",
            "15"=>"拉卡拉微信",
            "16"=>"招商银行",
            "17"=>"银联二维码"
       );
        $this->assign("page",$list->render());
        $this->assign("list",$list);
        $this->assign("count",$count);
        $this->assign("pay_type",$pay_type);
        $this->assign("starttime",$starttime);
        $this->assign("endtime",$endtime);
        $this->assign("type",input("type"));
        $this->assign("status",input("status"));
        return $this->fetch();
    }

    public function deal()
    {
     $result=(new System())->orderdeal();
        if(isset($result['message'])){
            exit(json_encode($result['message']));
        }else{
            exit(json_encode(1));
        }

    }
    /**
     * 订单列表导出excel
     */
    public function export($where)
    {

        $headArr = array("订单号","昵称","收货人姓名","收货号码","省份","城市","区/县","详细地址","下单时间","支付时间",
            '发货时间','完成时间',"商品名称","数量","规格","价格","状态");
        //$where['status']=1;
        $list = db("order")->alias("o")
            ->field("o.*,m.nickname,m.headimage,g.goods_name,g.goods_num,g.goods_price,g.spec_name")
            ->join("member m","o.user_id=m.id")
            ->join("order_goods g","g.order_id=o.id")
            ->order("id desc")
            ->where($where)
            ->select();
        $data=array();
        foreach($list as $k => $v){
            $data[$k][] = $v['order_sn'];
            $data[$k][] = $v['nickname'];
            $data[$k][] = $v['name'];
            $data[$k][] = $v['mobile'];
            $data[$k][] = $v['province'];
            $data[$k][] = $v['city'];
            $data[$k][] = $v['county'];
            $data[$k][] = $v['address'];
            $data[$k][] = date("Y-m-d H:i",$v['create_time']);
            $data[$k][] =!empty($v['pay_time'])?date("Y-m-d H:i",$v['pay_time']):'';
            $data[$k][] = !empty($v['shipping_time'])?date("Y-m-d H:i",$v['shipping_time']):'';
            $data[$k][] = !empty($v['finish_time'])?date("Y-m-d H:i",$v['finish_time']):'';
            $data[$k][] = $v['goods_name'];
            $data[$k][] = $v['goods_num'];
            $data[$k][] = $v['spec_name'];
            $data[$k][] = $v['goods_price'];
            //,0待付款，1已付款，2已发货，3已完成,,4退款中，-2已关闭，-1已退款
            switch($v['status']){
                case '0': $data[$k][]='待付款';break;
                case '1': $data[$k][]='已付款';break;
                case '2': $data[$k][]='已发货';break;
                case '3': $data[$k][]='已完成';break;
                case '4': $data[$k][]='退款中';break;
                case '-1': $data[$k][]='已退款';break;
                case '-2': $data[$k][]='已关闭';break;
            }
        }
        $filename='订单列表';
        (new Export())->ImportExcel($filename,$headArr,$data);
    }
    //订单详情
    public function detail()
    {
        $id = input('order_id');
        $condition['o.id'] = $id;
        if (!$id) {
            $this->error('参数有误');
        }
        $order = db('order')->alias('o')->join('member m', 'o.user_id=m.id')
            ->field('m.nickname,m.mobile,o.*')
            ->where($condition)
            ->find();
        $where['o.id'] = $id;
        $order_goods = db('order')->alias('o')
            ->field('o.*,g.goods_id,g.goods_name,g.goods_num,g.goods_price,g.market_price,spec_name,g.goods_image,g.param')
            ->join('order_goods g','g.order_id=o.id')
            ->where($where)
            ->select();
        foreach($order_goods as &$v){
            $v['goods_image']=IMG_PATH.$v['goods_image'];
        }
        unset($v);
        $this->assign('order_goods', $order_goods);
        $this->assign('order', $order);
        $this->assign('id', $id);

        return $this->fetch();
    }


    /*
     * 司机订单列表
     */
    public function driver_order_list()
    {
        $pageParam = ['query' =>[]];
        $where = [];
        $status=input('status');
        if(!empty($status)){
            $where['status'] =$status;
            $pageParam['query']['status'] = $status;
        }
        $this->assign('status', $status);
        $time = input('time');
        if(!empty($time)) {
            $today = strtotime(date("Y-m-d"),time());//1547049600
            $zuotian = strtotime(date("Y-m-d"),time())-24*60*60;//1546963200
            switch($time){
                case '1':
                    $where['send_time'] = ['>=',$today];
                    break;
                case '2':
                    $where['send_time'] = ['<',$today];
                    $where['send_time'] = ['>=',$zuotian];
                    break;
                case '3':
                    $where['send_time'] = ['<',$zuotian];
                    break;
            }
            $pageParam['query']['time'] = $time;
            $this->assign('time', $time);
        }
        $where['shop_id']=$this->user['shopid'];

        //订单数量
        $count = db('driver_order')->where($where)->count();

        $order = db('driver_order')
            ->where($where)
            ->order('id desc')
            ->paginate(15,false,$pageParam)->each(function($item,$key){
                $item['driver_info'] = db('driver')->where(['id'=>$item['driver_id']])->field('id,nickname,address,mobile,headimage,sex')->find();
                //订单数量
                $item['order_count'] = db('driver_order_info')->where(['driver_order_id'=>$item['id']])->count();
                $item['status'] = 0;
                return $item;
            });
//        halt($order);
        $this->assign('count', $count);
        $this->assign('list', $order);
        $this->assign('page', $order->render());
        return $this->fetch();
    }

    /*
     * 司机订单详情
     */
    public function driver_order_detail()
    {
        $id = input('id');
        $where['shop_id']=$this->user['shopid'];
        $where['id'] = $id;
//        $uid = 3;
        $driverorder = db('driver_order')->where($where)->find();
//        echo db('driver_order')->getLastSql();
        if(empty($driverorder))$this->error('参数有误');

        $order = db('driver_order_info')->where(['driver_order_id'=>$id])->order('num asc')->select();

        foreach($order as $k=>$v){
            $order_id= $order[$k]['order_id'];
            $order[$k]['order'] =  db('order')->where('id = '.$order_id)->field('id,order_sn,address,lng,lat,mobile,realname,send_status')->find();
        }

//        $order['driver_id'] = $driverorder['driver_id'];
//        $order['driver_nickname'] = db('driver')->where(['id'=>$driverorder['driver_id']])->value('nickname');
//        halt($order);
        $this->assign('list', $order);
        return $this->fetch();
    }

    /*
     * 重选司机
     */
    public function driver_order_setdriver()
    {
        if(request()->isAjax()){
            $id = input('id');
            $driver_id = input('driver_id');
            $driver_shop_where = ['shop_id'=>$this->user['shopid'],'driver_id'=>$driver_id,'status'=>1,'isbind'=>1];
            $res_driver_shop = db('driver_shop')->where($driver_shop_where)->find();
            if(empty($res_driver_shop))$this->error('参数有误');
            $where['id'] = $id;
            $where['shop_id'] = $this->user['shopid'];
            $db = db('driver_order');
            $res = $db->where($where)->find();
//            var_dump($res);
            if(empty($res))$this->error('参数有误');
            if($res['status'] == 2)return ['message'=>'该单已完成'];
            $data = [
                'driver_id'=>$driver_id,
                'status'=>0
            ];
            $res = $db->where($where)->update($data);
            if(!$res)$this->error('操作失败');
            $this->success('操作成功!');
        }
        $id = input('id');
        $this->assign('id', $id);
        $where['shop_id']=$this->user['shopid'];
        $where['status'] = 1;
        $where['isbind'] = 1;
        $list = db("driver_shop")->where($where)->order("id desc")->select();
        foreach($list as $key=>&$value){
            $value['driver'] = db('driver')->alias('d')
                ->where(['d.id'=>$value['driver_id']])
                ->field('d.sex,d.address,d.nickname,d.headimage,d.mobile')->find();
        }
        $this->assign('driver', $list);
        return $this->fetch();
    }

    public function getBestroute()
    {
        $search = [];//查出的存放点
        $shopid = $this->user['shopid'];
        $shop = db('shop')->where(['id'=>$shopid])->field('lat,lng')->find();
        //['lat'=>123.22,'lng'=>143.55];
        $top = $shop;//仓库点

        //筛选的数据
        $id = input('id');
        $where['shop_id']=$shopid;
        $where['id'] = $id;
//        $uid = 3;
        $driverorder = db('driver_order')->where($where)->find();
//        echo db('driver_order')->getLastSql();
        if(empty($driverorder))$this->error('参数有误');

        $ar = db('driver_order_info')->alias('do')
        ->join('order o', 'o.id = do.order_id')
        ->where(['do.driver_order_id'=>$id])
        ->field('do.*,o.lat,o.lng')
        ->select();

       $lenght = count($ar);
       if($lenght == 1){
           $ar[0]['dif'] = getDistance($top['lat'],$top['lng'],$ar[0]['lat'],$ar[0]['lng']);
            $search=$ar;
       }else{
            for($i=0; $i<$lenght;$i++){
                //找出第一点
                foreach($ar as $k=>&$v){
                    //计算距离
                    $v['dif'] = getDistance($top['lat'],$top['lng'],$v['lat'],$v['lng']);
                    // $v['dif'] = $v['a'] * $v['b'] - $top['a']*$top['b'];
                    $dif[$k] = $v['dif'];
               }
               array_multisort($dif, SORT_ASC, SORT_NUMERIC, $ar);
               $search[] = $ar[0];
               $top = $ar[0];
               unset($dif);
               unset($ar[0]);
            }
            
       }

//        var_dump($search);die;
        if(!empty($search)){
           foreach ($search as $key => $value) {
               $data[$key]['id'] = $value['id'];
               $data[$key]['num'] = $key+1;
               $distance = round($value['dif']/1000,2);
               $data[$key]['distance'] = $distance;
           }
//            var_dump($data);die;
            $driver_order_info = new DriverOrderInfo();
            $res = $driver_order_info->saveAll($data);
//            echo $driver_order_info->getLastSql();
//            $res = db('driver_order_info')->saveAll($data);
            if(!$res)$this->error('操作失败！');
            $this->success('操作成功!');
        }  
    }
}
